package org.springframework.beans.factory.config;

import org.springframework.beans.factory.anno.Component;
import org.springframework.beans.factory.anno.Configuration;
import org.springframework.beans.factory.util.ConfigurationClassUtils;
import org.springframework.beans.factory.util.StringUtils;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/14
 */
public class AnnotationBeanNameGenerator implements BeanNameGenerator {
    @Override
    public String generateBeanName(BeanDefinition bd) {
        if(bd instanceof AnnotatedBeanDefinition){
            String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition)bd);
            if (StringUtils.isNotBlank(beanName)) {
                return beanName;
            }
        }
        return buildDefaultBeanName(bd);
    }

    private String buildDefaultBeanName(BeanDefinition bd) {
        return StringUtils.toLowerCaseFirstOne(bd.getBeanClass().getSimpleName());
    }

    private String determineBeanNameFromAnnotation(AnnotatedBeanDefinition abd) {
        AnnotationMetadata metadata = abd.getMetadata();
        Map<String, Object> annoMap = null;
        if(metadata.hasAnnotation(Configuration.class)){
            annoMap =  metadata.getAnnotationAttributes(Configuration.class);
        }else if(metadata.hasAnnotation(Component.class)){
            annoMap =  metadata.getAnnotationAttributes(Component.class);
        }
        if(null!=annoMap&&annoMap.size()>0&&annoMap.containsKey(ConfigurationClassUtils.CONFIGURATION_VALUE)){
            return (String) annoMap.get(ConfigurationClassUtils.CONFIGURATION_VALUE);
        }
        return null;
    }
}
